package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"os"
	"path"
	"path/filepath"
	"socket/common"
	"strconv"
	"time"
)

type CommonController struct {
	//需要DB连接操作数据库
	DB *gorm.DB
}

func NewCommonController() CommonController {
	//自动迁移
	db := common.GetDB()
	return CommonController{DB: db}

}

func (c CommonController) Oss(ctx *gin.Context) {
	sign := common.GetOssSign()
	common.Success(ctx, gin.H{"data": sign}, "成功")
}

func (c CommonController) SendSms(ctx *gin.Context) {
	phone := "17335893564"
	code := "535897"
	err := common.SendSms(phone, code)
	if err != nil {
		return
	}
	common.Success(ctx, nil, "ok")
}

func (c CommonController) SendMail(ctx *gin.Context) {
	email := "906280213@qq.com"
	title := "邮箱验证"
	content := `
    <p> 请点击以下链接进行确认</p>
	<a target="_blank" href="https://www.baidu.com">https://www.baidu.com</a>
	`
	//异步发送
	go func() {
		err := common.SendMail(email, title, content)
		if err != nil {
			return
		}
	}()

	common.Success(ctx, nil, "ok")
}

func (c CommonController) LocalFile(ctx *gin.Context) {
	//var ext = ctx.PostForm("ext")
	file, err := ctx.FormFile("file")
	if err != nil {
		common.Server(ctx, "上传文件出错", nil)
		return
	}

	getYear := time.Now().Format("2006") //获取年
	getMonth := time.Now().Format("01")  //获取月
	getDay := time.Now().Format("02")    //获取日

	//服务器图片地址 /mnt/images
	savePath := "static/excel/" + getYear + "/" + getMonth + "/" + getDay

	exist, err := common.PathExists(savePath)
	if err != nil {
		common.Fail(ctx, "上传图片出错", nil)
		return
	}

	if !exist {
		err := os.MkdirAll(savePath, os.ModePerm)
		if err != nil {
			fmt.Printf("mkdir failed![%v]\n", err)
		} else {
			fmt.Printf("mkdir success!\n")
		}
	}
	ext := filepath.Ext(file.Filename)
	dst := path.Join(savePath, fmt.Sprintf("%s%s%s", strconv.FormatInt(time.Now().Unix(), 10), common.RandomCode(), ext))
	err = ctx.SaveUploadedFile(file, dst)
	if err != nil {
		return
	}
	common.Success(ctx, gin.H{"data": dst}, "成功")

}

func UploadFile(ctx *gin.Context) {
	//var ext = ctx.PostForm("ext")
	file, err := ctx.FormFile("file")
	if err != nil {
		common.Server(ctx, "上传文件出错", nil)
		return
	}

	getYear := time.Now().Format("2006") //获取年
	getMonth := time.Now().Format("01")  //获取月
	getDay := time.Now().Format("02")    //获取日

	//服务器图片地址 /mnt/images
	savePath := "files/file/" + getYear + "/" + getMonth + "/" + getDay

	exist, err := common.PathExists(savePath)
	if err != nil {
		common.Fail(ctx, "上传图片出错", nil)
		return
	}

	if !exist {
		err := os.MkdirAll(savePath, os.ModePerm)
		if err != nil {
			fmt.Printf("mkdir failed![%v]\n", err)
		} else {
			fmt.Printf("mkdir success!\n")
		}
	}
	ext := filepath.Ext(file.Filename)
	dst := path.Join(savePath, fmt.Sprintf("%s%s%s", strconv.FormatInt(time.Now().Unix(), 10), common.RandomCode(), ext))
	ctx.SaveUploadedFile(file, dst)
	common.Success(ctx, gin.H{"data": dst}, "成功")

}
